import { useContext, useState } from 'react'
import { Form, Button, Input, message, Popconfirm } from 'antd'
import { configContext, getLocalValue } from '../../config/env'

function Config() {
  const [form, setForm] = useState({
    fileUrl: localStorage.getItem('fileUrl') || 'http://37.187.149.182:8089',
    url: localStorage.getItem('url') || 'http://37.187.149.182:81'
  })

  const localValue = useContext(configContext)

  const updateFormValue = (e:any, type: string) => {
    setForm({
      ...form,
      [type]: e.target.value
    })
  }

  const updateData = async () => {
    message.success(getLocalValue(localValue, '保存成功', 'save successfully'))
    localStorage.setItem('fileUrl', form.fileUrl)
    localStorage.setItem('url', form.url)
    location.reload();
  }

  return ( 
     <div className='table-content'>
        <div className='title'>{getLocalValue(localValue, '服务配置', 'service configuration')}</div>
        <div className='table'>
          <Form style={{ maxWidth: 600 }} labelCol={{span: 13}}>
            <Form.Item label={getLocalValue(localValue, '文件系统同步工具地址', 'address of the file system synchronization tool')} style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} value={form.fileUrl} onChange={(e) => updateFormValue(e, 'fileUrl')} />
            </Form.Item>
            <Form.Item label={getLocalValue(localValue, 'Web管理服务后台地址', 'background address of the Web management service')} style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} value={form.url} onChange={(e) => updateFormValue(e, 'url')} />
            </Form.Item>
            <Form.Item wrapperCol={{offset: 9}}>
                <Popconfirm
                  placement="top"
                  title={getLocalValue(localValue, '提示', 'tip')}
                  description={getLocalValue(localValue, '是否确定保存?', 'confirm to save?')}
                  okText={getLocalValue(localValue, '确定', 'ok')}
                  cancelText={getLocalValue(localValue, '取消', 'cancel')}
                  onConfirm={updateData}
                >
                  <Button type="primary">{getLocalValue(localValue, '保存', 'save')}</Button>
                </Popconfirm>
            </Form.Item>
          </Form>
        </div>
     </div>
  );
}

export default Config